package middleware

import (
	"github.com/gin-gonic/gin"
	"im/app/models"
	"net/http"
	"strings"
)

func TokenCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
			// 仅支持2中token获取，1直接参数传_token 2是直接authorization标准头信息
			token, ok := c.GetQuery("_token")
			if !ok {
				hToken := c.GetHeader("Authorization")
				if len(hToken) < models.BearerLength {
					c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
						"code": 401,
						"message": "header Authorization has not Bearer token",
						"data": "",
					})
					return
				}
				token = strings.TrimSpace(hToken[models.BearerLength:])
			}
			admin, err := models.JwtParseUser(token)
			// 如果过期就去找reids是否存在上次的token 如果有，就刷新token，没有就验证失败，重新登录
			if err != nil {
				c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
					"code": 401,
					"message":  "token 验证失败",
					"data": "",
				})
				return

				//cacheToken, err := models.Rds.Get(token).Result()
				//if err != nil {
				//	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				//		"code": 401,
				//		"message": "token 验证失败",
				//		"data": "",
				//	})
				//	return
				//}
				//var mapCacheToken map[string]interface{}
				//err1 := json.Unmarshal([]byte(cacheToken), &mapCacheToken)
				//if err1 != nil {
				//	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				//		"code": 401,
				//		"message": "token 验证失败",
				//		"data": "",
				//	})
				//	return
				//}
				//admin_id := mapCacheToken["admin"].(map[string]interface{})["id"]
				//admin_new := models.Admins{}
				//err2 := models.Db.Where(" id = ?", admin_id).Find(&admin_new).Error
				//if err2 != nil {
				//	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				//		"code": 401,
				//		"message":  "token 验证失败",
				//		"data": "",
				//	})
				//	return
				//}
				//token_res,_ := models.JwtGenerateToken(admin, 12*3600 * time.Second)
				//result_json,_ := json.Marshal(token_res)
				//// 拿到第一次存的时间
				//sd := models.Rds.TTL(token_res["token"].(string)).Val()
				//err3 := models.Rds.Set(token_res["token"].(string),result_json, sd).Err()
				//if err3 != nil {
				//	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				//		"code": 401,
				//		"message":  "token 验证失败",
				//		"data": "",
				//	})
				//	return
				//}
				//c.Header("new_token", token_res["token"].(string))
				//c.Set(models.ContextKeyUserObj, &admin_new) // 存储到gin.Context
				//c.Next()
				//return
			}
			c.Set(models.ContextKeyUserObj, admin) // 存储到gin.Context

			c.Next()
			return
	}
}